// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.asm;

import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.MethodNode;

/**
 * Supplier of methods.
 * 
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public abstract class MethodSupplier {
  /**
   * Supplies a method and accepts given visitor on it.
   * 
   * @param visitor method visitor to accept on supplied method.
   */
  public abstract void accept(MethodVisitor visitor);
  
  /**
   * Returns supplier of given method node.
   * 
   * @param method method node
   * @return supplier of method node
   */
  public static MethodSupplier of(final MethodNode method) {
    return new MethodSupplier() {
      @Override
      public void accept(MethodVisitor visitor) {
        method.accept(visitor);
      }
    };
  }
  
  public static MethodSupplier of(
      final ClassSupplier classSupplier,
      final String methodName, 
      final String methodDesc) {
    
    return new MethodSupplier() {
      @Override
      public void accept(final MethodVisitor methodVisitor) {
        classSupplier.accept(
            new BaseClassVisitor() {
              @Override
              public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                  String[] exceptions) {
                if (name.equals(methodName) && desc.equals(methodDesc)) {
                  return methodVisitor;
                } else {
                  return null;
                }
              }      
            });
      }
    };
  }
}
